package cn.com.czpb.client.module.news.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;

import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.app.MToolBarActivity;
import cn.com.czpb.client.app.MyActivitymanager;
import cn.com.czpb.client.model.event.PraiseEvent;
import cn.com.czpb.client.model.news.ComResultEntity;
import cn.com.czpb.client.model.news.EmptyEntityList;
import cn.com.czpb.client.model.news.IsCollectionEntity;
import cn.com.czpb.client.model.news.NewsBean;
import cn.com.czpb.client.model.news.NewsDetailBean;
import cn.com.czpb.client.model.news.NewsDetailEntity;
import cn.com.czpb.client.model.news.NewsRelateEntity;
import cn.com.czpb.client.model.news.PraiseNumEntity;
import cn.com.czpb.client.model.usercenter.LevelEntity;
import cn.com.czpb.client.module.dialog.ShareDialog;
import cn.com.czpb.client.module.news.adapter.NewsItemListViewAdapterNew;
import cn.com.czpb.client.module.news.dialog.InputPop;
import cn.com.czpb.client.module.news.view.MyWebView;
import cn.com.czpb.client.module.personal.WodeFragment;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.ActionbarUtils;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.PageCtrl;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.StringUtils;
import cn.com.czpb.client.utils.TUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by 猪猪侠 on 2017/8/14.
 */
public class NewsDetailActivity extends MToolBarActivity implements BaseQuickAdapter.OnItemChildClickListener, MyWebView.PlayListener {
    @BindView(R.id.rv_news_id)
    RecyclerView rvNewsId;//recycleview
    @BindView(R.id.news_detail_ll_bottom1)
    LinearLayout bottomll;
    @BindView(R.id.img_back)
    LinearLayout imgBack;

    @BindView(R.id.comment_number_tx)
    TextView commentNumberTx;
    @BindView(R.id.ll_newdetail_comments)
    LinearLayout llNewdetailComments;
    @BindView(R.id.praise_number_tx)
    TextView praiseNumberTx;
    @BindView(R.id.ll_newdetail_praise)
    LinearLayout llNewdetailPraise;
    @BindView(R.id.collection_number_tx)
    TextView collectionNumberTx;
    @BindView(R.id.ll_newdetail_collection)
    LinearLayout llNewdetailCollection;
    @BindView(R.id.share_number_tx)
    TextView shareNumberTx;
    @BindView(R.id.ll_newdetail_share)
    LinearLayout llNewdetailShare;
    @BindView(R.id.img_comment)
    ImageView imgComment;
    @BindView(R.id.img_praise)
    ImageView imgPraise;
    @BindView(R.id.img_collection)
    ImageView imgCollection;
    @BindView(R.id.img_share)
    ImageView imgShare;



    @BindView(R.id.ll_bottom_id)
    LinearLayout ll_bottom_id;

    @BindView(R.id.img_play_id)
    ImageView img_play_id;
    @BindView(R.id.tv_title_id)
    TextView tvTitleId;
    @BindView(R.id.tv_double_id)
    TextView tvDoubleId;
    @BindView(R.id.tv_time_id)
    TextView tvTimeId;
//    @BindView(R.id.home_read)
//    ImageView home_read;


    private NewsItemListViewAdapterNew adapter;
    private NewsBean nb;
    private NewsDetailBean ndb;
    private InputPop inputPop;
    private String tid;
    private String voteflag;
    private String sharelink = "";
    private MyWebView mywebview;

    int t = 60;
    private Timer timer;
    private boolean isPlay = false;
    private SpeechSynthesizer mTts;
    private String[] items_double= new String[]{"0.8X", "1X","1.5X","2X"};
    private String[] items_time= new String[]{"5分钟后", "15分钟后","30分钟后","不开启定时"};
//    private boolean isFirst = true;
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;
    //发音人
    private int selectedNum = 0;
    // 默认发音人
    private String voicer = "xiaoyan";

    private static final String TAG = "NewsDetailActivity";

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (333 == msg.what) {
                try {
                    tvTimeId.setText(t + "'");
                    t--;
                    if (t < 0) {
                        resetTimer();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            if (666 == msg.what) {
                try {
                        firstPlay();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            if (777 == msg.what) {
//                if (spu.getUser() == null) {
//                    PageCtrl.start2LoginActivity((Activity) mContext);
//                }

            }
//            if (888 == msg.what) {
//                    //作者个人主页
////                 String uid = msg.getData().getString("uid");
////                 String tid = msg.getData().getString("tid");
//                    PageCtrl.start2SubscribeDetailActivity(activity,uid,tid);
//
//            }
        }
    };

    @Override
    protected int setLayoutId() {
        return R.layout.activity_news_detail;
    }

    @Override
    public void initView() {

//        setBackVisiable(false);
        ActionbarUtils.setMeizuStatusBarDarkIcon(activity, true);
        ActionbarUtils.setMiuiStatusBarDarkMode(activity, true);
//        settitleBg();
        LinearLayoutManager manager = new LinearLayoutManager(activity);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rvNewsId.setLayoutManager(manager);
        adapter = new NewsItemListViewAdapterNew(activity,null, false);
        adapter.setOnItemChildClickListener(this);
        rvNewsId.setAdapter(adapter);
    }

    @Override
    public void initData() {
        switch (spu.getSpeed()){
            case "40":
                tvDoubleId.setText("0.8X");
                break;
            case "50":
                tvDoubleId.setText("1.0X");
                break;
            case "75":
                tvDoubleId.setText("1.5X");
                break;
            case "100":
                tvDoubleId.setText("2.0X");
                break;

            default:
                tvDoubleId.setText("1.0X");
                break;
        }

        Intent intent = getIntent();
        nb = (NewsBean) intent.getSerializableExtra("newbean");
        tid = intent.getStringExtra("tid");
        voteflag = intent.getStringExtra("voteflag");
            getNewsDetails();



    }

    /**
     * 获取新闻
     */
    // TODO: 2017/8/14  
    private void getNewsDetails() {
        LogUtils.i("nid-->" + nb.getNid());
        Map<String, String> map = new HashMap<>();
//        if (spu.getUser() != null) {
//            map.put("uid", spu.getUser().getUid());
//        }
        map.put("nid", nb.getNid());
        map.put("device", DeviceUtils.getMyUUID(this));
        Factory.provideHttpService()
                .newsDetail(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsDetailEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsDetailEntity entity) {
                        LogUtils.i("detail-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsDetailEntity>() {
                    @Override
                    public void call(NewsDetailEntity entity) {
                        ndb = entity.data;
                        setNewsData();
                        addVisits(ndb.getTid());
                        Log.e("entity.data:",entity.data.toString());

                        if ("1".equals(entity.data.getIsfavorite())) {
                            imgCollection.setImageResource(R.drawable.tabbar_collect_light);
                        } else {
                            imgCollection.setImageResource(R.drawable.tabbar_collect);
                        }
                        if ("1".equals(entity.data.getIspraise())) {
                            imgPraise.setImageResource(R.drawable.tabbar_like_light);
                        } else {
                            imgPraise.setImageResource(R.drawable.tabbar_like);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("detail-->throwable-->" + throwable);
                    }
                });
    }

    private String URL;

    // 设置新闻详情
    private void setNewsData() {

        //获取相关推荐新闻
        if (null == ndb) {
            return;
        }
        commentNumberTx.setText(ndb.getComcount());
        LogUtils.e("praisecount:"+ndb.getPraisecount());
        praiseNumberTx.setText(ndb.getPraisecount());
        collectionNumberTx.setText(ndb.getFavoritecount());
        String url = nb.getNewsurl();
        LogUtils.i("url-->"+url);
//        if (ndb.getVoteflag() != null && ndb.getVoteflag().equals("1")) {
//            if (!StringUtils.isEmpty(ndb.getNewsurl())) {
////                if (null == spu.getUser()) {
//                    URL = InterfaceJsonfile.VOTEURL + nb.getNid() + "/uid//device/" + DeviceUtils.getIMEI(this);
////                } else {
////                    URL = InterfaceJsonfile.VOTEURL + nb.getNid() + "/uid/" + spu.getUser().getUid() + "/device/" + DeviceUtils.getIMEI(this);
////                }
//            } LogUtils.i("url2-->"+URL);
//
//        } else {
//
//            if (!StringUtils.isEmpty(nb.getNewsurl())) {
//
////                if (null == spu.getUser()) {
//                    URL = url + "?nid=" + nb.getNid() + "&uid=&math=" + Math.random() + "&device=" + DeviceUtils.getIMEI(this);
////                } else {
////
////                    URL = url + "?uid=" + spu.getUser().getUid() + "&nid=" + nb.getNid() + "&math=" + Math.random() + "&device=" + DeviceUtils.getIMEI(this);
////                }
//            }
//        }
        if (StringUtils.isEmpty(URL)) {
            URL = url;
        }
        LogUtils.e("url-4->" + URL);
        MyWebView.hidewhile404 my404interface = new MyWebView.hidewhile404() {
            @Override
            public void hide() {
//                if(bottomll != null) {
//                    bottomll.setVisibility(View.GONE);
//                }
            }
        };
        mywebview = MyWebView.instance(this, ndb, tid,my404interface,handler);
        mywebview.setOnPlayClickListener(this);
        adapter.addHeaderView(mywebview.getView(url));
        getRelateNews(ndb.getNid());
        //TODO
    }

    //添加浏览量
    public void addVisits(String tid) {
        Map<String, String> map = new HashMap<>();
        map.put("nid", nb.getNid());
        map.put("type", "1");
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("num", "1");
        map.put("tid", tid);

//        if (spu.getUser() != null) {
//            map.put("uid", spu.getUser().getUid());
//        }

        map.put("device", DeviceUtils.getMyUUID(activity));
        Factory.provideHttpService().addvisit(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<EmptyEntityList, Boolean>() {
                    @Override
                    public Boolean call(EmptyEntityList emptyEntityList) {
                        return true;
                    }
                })

                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<EmptyEntityList>() {
                    @Override
                    public void call(EmptyEntityList emptyEntityList) {
                        LogUtils.i("emptyEntityList----" + emptyEntityList.code);
                    }

                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });
    }

    @OnClick({R.id.img_back, R.id.ll_newdetail_comments, R.id.ll_newdetail_praise, R.id.ll_newdetail_collection, R.id.ll_newdetail_share
            ,R.id.ll_read
            ,R.id.img_close_id
            ,R.id.tv_double_id
            ,R.id.tv_time_id
            ,R.id.img_play_id
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                if(mywebview != null && mywebview.canGoBack()){
                    mywebview.goback();
                }else {
                    this.finish();
                }
                break;
            case R.id.ll_newdetail_collection:
//                if (spu.getUser() != null) {
                    addCollection();
//                } else {
//                    PageCtrl.start2LoginActivity(activity);
//                }
                break;
            case R.id.ll_newdetail_share:
//                if(spu.getUser() != null) {
                    String imgurl = null;
                    if (null != ndb.getImgs() && ndb.getImgs().size() > 0) {
                        imgurl = ndb.getImgs().get(0);
                    }
                    if(StringUtils.isEmpty(imgurl)){
                        imgurl = getResources().getString(R.string.shared_img);
                    }
                    if(ndb.getRtype().equals("4")){
//                        sharelink = ndb.getNewsurl();
                        sharelink = mywebview.getWebviewUrl();
                    }else {
                        if (spu.getUser()!=null){
                            sharelink = InterfaceJsonfile.BASEURL + ndb.getNid() + "/uid/" + spu.getUser().getUid();
                        }else{
                            sharelink = InterfaceJsonfile.BASEURL + ndb.getNid();
                        }

                    }
                    ShareDialog dialog = new ShareDialog(activity, R.style.Sharedialog, ndb.getTitle(), sharelink, imgurl, 1);
                    dialog.show();
//                }else{
//                    PageCtrl.start2LoginActivity(activity);
//                }
                break;
            case R.id.ll_newdetail_comments:
//                if (spu.getUser() != null) {

                    if (ndb.getRtype().equals("5")) {
                        PageCtrl.startCommActivity(activity, ndb.getRvalue(), "1", "NEWS", ndb.getRvalue(), ndb);
                    } else {
                        PageCtrl.startCommActivity(activity, nb.getNid(), "1", "NEWS", nb.getNid(), ndb);
                    }
//                } else {
//                    PageCtrl.start2LoginActivity(activity);
//                }

                LogUtils.e("nid----", nb.getNid());
                break;
            case R.id.ll_newdetail_praise:


                praiseContent();
                break;

//            case R.id.ll_read:
//                if (isFirst){
//                    firstPlay();
//                }else{
//                    if (isPlay){
//                        home_read.setImageResource(R.drawable.read1);
//                        img_play_id.setImageResource(R.drawable.start);
//                        mTts.pauseSpeaking();
//                        isPlay =false;
//                    }else {
//                        Glide.with(this).load(R.drawable.read1_gif).into(home_read);
//                        Glide.with(this).load(R.drawable.bof_gif).asGif().into(img_play_id);
//                        mTts.resumeSpeaking();
//                        isPlay =true;
//                    }
//                }
//
//                break;
            case R.id.img_close_id:
                //隐藏关闭读报
//                isFirst =true;
                mTts.stopSpeaking();
//                home_read.setImageResource(R.drawable.read1);
                ll_bottom_id.setVisibility(View.GONE);
                img_play_id.setImageResource(R.drawable.start);
                break;
            case R.id.tv_double_id:
                new AlertDialog.Builder(activity).
                        setTitle("语速设置")
                        .setItems(items_double, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                switch (i){
                                    case 0:
                                        tvDoubleId.setText("0.8X");
                                        spu.setSpeed("40");
                                        firstPlay();
                                        break;
                                    case 1:
                                        tvDoubleId.setText("1.0X");
                                        spu.setSpeed("50");
                                        firstPlay();
                                        break;
                                    case 2:
                                        tvDoubleId.setText("1.5X");
                                        spu.setSpeed("75");
                                        firstPlay();
                                        break;
                                    case 3:
                                        tvDoubleId.setText("2.0X");
                                        spu.setSpeed("100");
                                        firstPlay();
                                        break;
                                }
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                }).setCancelable(true).show();
                break;
            case R.id.tv_time_id:
                new AlertDialog.Builder(activity).
                        setTitle("选择关闭时间")
                        .setItems(items_time, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                switch (i){
                                    case 0:
                                        tvTimeId.setText("5'");
                                        startTime();
                                        t=5;
                                        break;
                                    case 1:
                                        tvTimeId.setText("15'");
                                        t=15;
                                        startTime();
                                        break;
                                    case 2:
                                        tvTimeId.setText("30'");
                                        t=30;
                                        startTime();
                                        break;
                                    case 3:
                                        tvTimeId.setText("定时");
                                        if (null==timer){
                                            return;
                                        }
                                        timer.cancel();
                                        break;
                                }
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                }).setCancelable(true).show();
                //开启倒计时
                LogUtils.i("5秒倒计时");
                break;
            case R.id.img_play_id:
                //播放
                if (isPlay){
//                    home_read.setImageResource(R.drawable.read1);
                    img_play_id.setImageResource(R.drawable.start);
                    mTts.pauseSpeaking();
                    isPlay =false;
                }else {
//                    Glide.with(this).load(R.drawable.read1_gif).into(home_read);
                    Glide.with(this).load(R.drawable.bof_gif).asGif().into(img_play_id);
                    mTts.resumeSpeaking();
                    isPlay =true;
                }
                break;
        }
    }


    private void initlevel() {
        String uid = spu.getUser().getUid();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        Factory.provideHttpService().MyLevel(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<LevelEntity, Boolean>() {
                    @Override
                    public Boolean call(LevelEntity levelEntity) {

                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<LevelEntity>() {
                    @Override
                    public void call(LevelEntity levelEntity) {
                        LogUtils.e("code--" + levelEntity.code);
                        if ("200".equals(levelEntity.code)) {
                            spu.getUser().setUlevel("Lv" + levelEntity.data.getUserinfo().getLevel());
                            Intent intent = new Intent();
                            intent.setAction(WodeFragment.ACTION_USER);
                            activity.sendBroadcast(intent);

                        } else {
                            TUtils.toast(levelEntity.msg);
                        }

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.e("throwable------" + throwable.getMessage());
                    }
                });
    }

    //发表评论接口
    private void sendComment(String content, String cid) {
        Map<String, String> map = new HashMap<>();
        map.put("nid", ndb.getNid());
        map.put("uid", spu.getUser().getUid());
        map.put("type", "NEWS");
        map.put("content", content);
        map.put("title", ndb.getTitle());
        map.put("json_url", ndb.getNewsurl());//随便传一个
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .newsComment(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<ComResultEntity, Boolean>() {
                    @Override
                    public Boolean call(ComResultEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ComResultEntity>() {
                    @Override
                    public void call(ComResultEntity entity) {
                        if ("200".equals(entity.code)) {
                            TUtils.toast("评论成功");

                            commentNumberTx.setText(entity.data.getComcount());
                            initlevel();
                        } else {
                            TUtils.toast(entity.msg);
                        }
//                            setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        TUtils.toast("评论失败");
                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        try{
            if ((keyCode == KeyEvent.KEYCODE_BACK) && !mywebview.getWebviewUrl().equals("about:blank")) {
                if(mywebview.canGoBack()){
                    mywebview.goback();
                }else{
                    finish();
                }
                return false;
            }else {
                return super.onKeyDown(keyCode, event);
            }
        }catch (Exception e){
            return super.onKeyDown(keyCode, event);
        }

    }

    //是否收藏
    private void isCollection() {
        Map<String, String> map = new HashMap<>();
        if (spu.getUser() == null) {
            return;
        }
        map.put("typeid", ndb.getNid());
        map.put("uid", spu.getUser().getUid());
        map.put("type", "1");
        Factory.provideHttpService()
                .newsIsCollection(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<IsCollectionEntity, Boolean>() {
                    @Override
                    public Boolean call(IsCollectionEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200收藏-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<IsCollectionEntity>() {
                    @Override
                    public void call(IsCollectionEntity entity) {
                        if ("200".equals(entity.code)) {
                            if ("1".equals(entity.data.getStatus())) {
                                imgCollection.setImageResource(R.drawable.tabbar_collect_light);
                                collectionNumberTx.setText(entity.data.getFavcount());
                            }
                        } else {
                            collectionNumberTx.setText(entity.data.getFavcount());
                            TUtils.toast(entity.msg);
                        }
//                        setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("throwable------"+throwable.toString());                    }
                });
    }

    // 添加收藏
    private void addCollection() {
        Map<String, String> map = new HashMap<>();
        map.put("typeid", nb.getNid());
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("device", DeviceUtils.getMyUUID(activity));
        Factory.provideHttpService()
                .newsAddCollection(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<IsCollectionEntity, Boolean>() {
                    @Override
                    public Boolean call(IsCollectionEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        TUtils.toast("收藏成功"+entity.msg);
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<IsCollectionEntity>() {
                    @Override
                    public void call(IsCollectionEntity entity) {
                        if ("200".equals(entity.code)) {
                            if ("1".equals(entity.data.getStatus())) {
                                TUtils.toast("收藏成功");
                                initlevel();
                                imgCollection.setImageResource(R.drawable.tabbar_collect_light);
                                collectionNumberTx.setText(entity.data.getFavcount());
                            } else {
                                imgCollection.setImageResource(R.drawable.tabbar_collect);
                                collectionNumberTx.setText(entity.data.getFavcount());
                                TUtils.toast("收藏取消");
                            }
                        } else {
                            TUtils.toast(entity.msg);
                        }
//                        setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });
    }

    //赞
    private void praiseContent() {
        Map<String, String> map = new HashMap<>();
//        if (spu.getUser() != null) {
//            map.put("uid", spu.getUser().getUid());
//        }
        map.put("device", DeviceUtils.getMyUUID(activity));
        map.put("nid", ndb.getNid());
        map.put("tid", ndb.getTid());
        map.put("type", ndb.getRtype());
        map.put("siteid", "1");
        LogUtils.i("type-->"+ndb.getRtype());
        Factory.provideHttpService().praiseContent(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<PraiseNumEntity>() {
                    @Override
                    public void call(PraiseNumEntity baseEntity) {
LogUtils.i("praise-->"+baseEntity.msg);
                        if ("200".equals(baseEntity.code)) {
                            imgPraise.setImageResource(R.drawable.tabbar_like_light);

                            String count = praiseNumberTx.getText().toString();
                            try{
                                int countNew = Integer.parseInt(count)+1;
                                praiseNumberTx.setText(countNew+"");
                            }catch (Exception e){
                                e.printStackTrace();
                            }

//                            praiseNumberTx.setText(baseEntity.data.getPraisecount());
                            PraiseEvent praiseEvent = new PraiseEvent();
                            praiseEvent.setNid(ndb.getNid());
                            praiseEvent.setPraisecount(baseEntity.data.getPraisecount());
                            EventBus.getDefault().post(praiseEvent);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("praise-->"+throwable);
                    }
                });

    }


    //获取相关新闻列表
    private void getRelateNews(String nid) {
        LogUtils.i("init", "getNewslist");
        Map<String, String> map = new HashMap<>();
        map.put("nid", nid);
        Factory.provideHttpService()
                .newsRelageList(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsRelateEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsRelateEntity entity) {

                        if ("200".equals(entity.code)) {
                            LogUtils.i("200--list>成功");
                            return true;
                        }
                        LogUtils.i("200--list>失败");
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsRelateEntity>() {
                    @Override
                    public void call(NewsRelateEntity entity) {
                        if ("200".equals(entity.code)) {
                            setListData(entity.data.getList());
                        } else {
                            TUtils.toast(entity.msg);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("异常-->" + throwable.toString());
                        adapter.loadMoreFail();
                    }
                });


    }

    public void setListData(List<NewsBean> list) {
        adapter.addHeaderView(getLayoutInflater().inflate(R.layout.view_relate, null));
        adapter.addData(list);
        adapter.notifyDataSetChanged();
        adapter.loadMoreComplete();
        LogUtils.i("size-->" + adapter.getData().size());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        //语音功能
        mTts = SpeechSynthesizer.createSynthesizer(activity,null);
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        NewsBean newsBean = (NewsBean) adapter.getItem(position);
        switch (view.getId()) {
            case R.id.newsItem_root:
                MyActivitymanager.pushActivity(activity, newsBean, "", "newsitem", newsBean.getRvalue());
                break;
        }
    }
    @Override
    public void finish() {
        if (mTts!=null){
            mTts.stopSpeaking();
        }
        if (mywebview.getWebview()!=null){
            mywebview.getWebview().loadUrl("about:blank");
        }
        super.finish();
    }

    private void resetTimer() {
        if (null==timer){
            return;
        }
        timer.cancel();
        tvTimeId.setText("定时");
//        isFirst =true;
        //隐藏关闭读报
        mTts.stopSpeaking();
        ll_bottom_id.setVisibility(View.GONE);
    }

    public  void playMusic(){
        LogUtils.i("cotent-->"+ndb.getContent());
        String text = ndb.getContent();
        if (  StringUtils.isEmpty(text) ){
            playMusic();
            return;
        }
        LogUtils.i("title-->"+ndb.getTitle());
        tvTitleId.setText(ndb.getTitle());
        mTts.startSpeaking(text,mTtsListener);
//        Glide.with(this).load(R.drawable.read1_gif).into(home_read);
        Glide.with(this).load(R.drawable.bof_gif).asGif().into(img_play_id);
    }

    public void firstPlay(){
        LogUtils.i("play-->2");
        ll_bottom_id.setVisibility(View.VISIBLE);
        isPlay =true;
//        isFirst = false;
        setParam();
        playMusic();

    }
    private void startTime() {
        if (timer!=null){
            timer.cancel();
        }
        timer=new Timer();
        TimerTask tt=new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(333);
            }
        };
        timer.schedule(tt,0,5000);
    }




    //语音功能
    /**
     * 参数设置
     * @return
     */
    private void setParam(){
        // 清空参数
        if (null!=mTts){
            mTts.setParameter(SpeechConstant.PARAMS, null);
        }else {
            mTts = SpeechSynthesizer.createSynthesizer(activity,null);
        }
        // 根据合成引擎设置相应参数
        if(mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
            // 设置在线合成发音人
            mTts.setParameter(SpeechConstant.VOICE_NAME, voicer);
            //设置合成语速
            mTts.setParameter(SpeechConstant.SPEED, spu.getSpeed());
            //设置合成音调
            mTts.setParameter(SpeechConstant.PITCH, "50");
            //设置合成音量
            mTts.setParameter(SpeechConstant.VOLUME,  "50");
        }
        else {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
            // 设置本地合成发音人 voicer为空，默认通过语记界面指定发音人。
            mTts.setParameter(SpeechConstant.VOICE_NAME, "");
            /**
             * TODO 本地合成不设置语速、音调、音量，默认使用语记设置
             * 开发者如需自定义参数，请参考在线合成参数设置
             */
        }
        //设置播放器音频流类型
        mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");
        // 设置播放合成音频打断音乐播放，默认为true
        mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory()+"/msc/tts.wav");
    }
    /**
     * 合成回调监听。
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {

        @Override
        public void onSpeakBegin() {
            Log.e(TAG, "onSpeakBegin:开始播放 ", null);
        }

        @Override
        public void onSpeakPaused() {
            Log.e(TAG, "onSpeakBegin:暂停播放 ", null);
//            showTip("暂停播放");
        }

        @Override
        public void onSpeakResumed() {
            Log.e(TAG, "onSpeakBegin:继续播放 ", null);
//            showTip("继续播放");
        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos,
                                     String info) {
            // 合成进度
//            mPercentForBuffering = percent;
//            showTip(String.format(getString(R.string.tts_toast_format),
//                    mPercentForBuffering, mPercentForPlaying));
        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
            // 播放进度
//            mPercentForPlaying = percent;
//            showTip(String.format(getString(R.string.tts_toast_format),
//                    mPercentForBuffering, mPercentForPlaying));
        }

        @Override
        public void onCompleted(SpeechError error) {
            if (error == null) {
                mTts.stopSpeaking();
                ll_bottom_id.setVisibility(View.GONE);
            }
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //		Log.d(TAG, "session id =" + sid);
            //	}
        }
    };

public void playMMusic(){
//    LogUtils.i("play-->3"+isFirst);
//    if (isFirst){
//        firstPlay();
//    }else{
        if (isPlay){
//            home_read.setImageResource(R.drawable.read1);
            img_play_id.setImageResource(R.drawable.start);
            mTts.pauseSpeaking();
            isPlay =false;
        }else {
//            Glide.with(this).load(R.drawable.read1_gif).into(home_read);
            Glide.with(this).load(R.drawable.bof_gif).asGif().into(img_play_id);
            mTts.resumeSpeaking();
            isPlay =true;
        }
    }
//}
    @Override
    public void playMM() {

//        if (isFirst){
//            firstPlay();
//        }else{
            if (isPlay){
//                home_read.setImageResource(R.drawable.read1);
                img_play_id.setImageResource(R.drawable.start);
                mTts.pauseSpeaking();
                isPlay =false;
            }else {
//                Glide.with(this).load(R.drawable.read1_gif).into(home_read);
                Glide.with(this).load(R.drawable.bof_gif).asGif().into(img_play_id);
                mTts.resumeSpeaking();
                isPlay =true;
            }
//        }
    }
}
